package malus.shaofeng.com.beiwomusic.fragment;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.activity.ActivityUserMessage;
import malus.shaofeng.com.beiwomusic.activity.SpaceMessageActivity;
import malus.shaofeng.com.beiwomusic.activity.SpaceSettingActivity;
import malus.shaofeng.com.beiwomusic.model.LoginUser;
import malus.shaofeng.com.beiwomusic.utils.AccessTokenKeeper;
import malus.shaofeng.com.beiwomusic.utils.BitmapHelper;
import malus.shaofeng.com.beiwomusic.utils.Constants;
import malus.shaofeng.com.beiwomusic.utils.SPHelper;
import malus.shaofeng.com.beiwomusic.utils.UserHelper;
import malus.shaofeng.com.beiwomusic.utils.UsersAPI;
import malus.shaofeng.com.beiwomusic.view.Topbar;

/**
 * 我的空间
 */
public class MainMySpaceFragment extends Fragment implements RadioGroup.OnCheckedChangeListener, Topbar.onTopbarClickListener, View.OnClickListener {
    RadioGroup rgSelect;
    List<Fragment> fragmentList;
    private FragmentTransaction transaction;
    private Topbar topbar;
    private LinearLayout userInfo;
    //绑定登录
    Button mLogin;
    private AuthInfo mAuthInfo;
    private SsoHandler mSsoHandler;
    private Oauth2AccessToken mAccessToken;

    Dialog loginDialog;
    //三方登录按钮
    ImageButton qqLogin;
    ImageButton weiboLogin;
    //用户信息
    ImageView userIcon;
    ImageView userAuthor;
    ImageView userSex;
    TextView userNickname;
    TextView userLocation;

    UsersAPI mUsersAPI;


    public MainMySpaceFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_main_my_space, container, false);
        rgSelect=(RadioGroup)inflate.findViewById(R.id.space_radio_selector);
        topbar=(Topbar)inflate.findViewById(R.id.topbar);
        topbar.setOnTopbarClickListener(this);
        initView();
        rgSelect.setOnCheckedChangeListener(this);
        inflate.findViewById(R.id.space_email).setOnClickListener(this);
        userInfo=(LinearLayout)inflate.findViewById(R.id.fragment_main_my_space_userinfo);
        userInfo.setOnClickListener(this);

        mAuthInfo =
                new AuthInfo(
                        getActivity(),
                        Constants.Weibo.APP_KEY,
                        Constants.Weibo.REDIRECT_URL,
                        Constants.Weibo.SCOPE);
        mSsoHandler = new SsoHandler(getActivity(), mAuthInfo);
        mAccessToken = AccessTokenKeeper.readAccessToken(getActivity());
        //用户信息
        mLogin=(Button)inflate.findViewById(R.id.fragment_main_my_space_login);
        mLogin.setOnClickListener(this);

        userIcon=(ImageView)inflate.findViewById(R.id.my_space_user_icon);
        userAuthor=(ImageView)inflate.findViewById(R.id.my_space_user_author);
        userSex=(ImageView)inflate.findViewById(R.id.my_space_user_sex);
        userNickname=(TextView)inflate.findViewById(R.id.my_space_user_nickname);
        userLocation=(TextView)inflate.findViewById(R.id.my_space_user_location);

        checkUserLogin();

        return inflate;
    }

    @Override
    public void onResume() {
        super.onResume();
        setUserInfo();
    }

    /**
     * 检测用户是否登录
     */
    private void checkUserLogin() {
        //TODO 需要判断QQ账号是否登录
        if(TextUtils.isEmpty(mAccessToken.getToken())){
            //TODO 当没有微博信息时
            userInfo.setVisibility(View.GONE);
            mLogin.setVisibility(View.VISIBLE);
            loginDialog=new Dialog(getActivity());
            View dialogLayout=LayoutInflater.from(getActivity()).inflate(R.layout.item_activity_user_message_oauth_dialog,null);
            loginDialog.setContentView(dialogLayout);
            qqLogin=(ImageButton)dialogLayout.findViewById(R.id.user_login_qq);
            weiboLogin=(ImageButton)dialogLayout.findViewById(R.id.user_login_weibo);
            loginDialog.getWindow().setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.transaction));
            qqLogin.setOnClickListener(this);
            weiboLogin.setOnClickListener(this);
        }else{
            userInfo.setVisibility(View.VISIBLE);
            mLogin.setVisibility(View.GONE);
            //有微博信息
            setUserInfo();
        }
    }

    /**
     * 有账号，设置用户信息
     */
    private void setUserInfo() {
        UserHelper userHelper = UserHelper.getInstance();
        LoginUser user = userHelper.getUser();
        if(!TextUtils.isEmpty(user.getNickname())){
            userNickname.setText(user.getNickname());
        }
        String location="";
        if(!TextUtils.isEmpty(user.getProvince())){
            location+=user.getProvince();
        }
        if(!TextUtils.isEmpty(user.getCity())){
            location+=user.getCity();
        }
        userLocation.setText(location);

        if(user.getAuthor()==0){
            userAuthor.setImageDrawable(getResources().getDrawable(R.drawable.not_author_tag));
        }else  if(user.getAuthor()==1){
            userAuthor.setImageDrawable(getResources().getDrawable(R.drawable.author1));
        }else  if(user.getAuthor()==2){
            userAuthor.setImageDrawable(getResources().getDrawable(R.drawable.author2));
        }else  if(user.getAuthor()==3){
            userAuthor.setImageDrawable(getResources().getDrawable(R.drawable.author3));
        }
        if(user.getSex()==2){
            userSex.setImageDrawable(getResources().getDrawable(R.drawable.image_content_boy));
        }else{
            userSex.setImageDrawable(getResources().getDrawable(R.drawable.image_content_girl));
        }

        if(!TextUtils.isEmpty(user.getFace_uri())){
            BitmapUtils bitmapUtils = BitmapHelper.getBitmapUtils();
            String face_uri = user.getFace_uri();
            String imageUrl = BitmapHelper.getImageUrl(face_uri);
            bitmapUtils.display(userIcon, imageUrl, new BitmapLoadCallBack<ImageView>() {
                @Override
                public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                    int width = bitmap.getWidth();
                    Bitmap dst = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
                    Paint paint = new Paint();
                    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                    Canvas canvas = new Canvas(dst);
                    canvas.drawCircle(width / 2, width / 2, width / 2, paint);
                    imageView.setImageBitmap(dst);
                }

                @Override
                public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {

                }
            });
        }
    }


    /**
     * 授权后存储数据信息
     */
    private void setUserInfoAfterAuth(){
        mUsersAPI = new UsersAPI(getActivity(), Constants.Weibo.APP_KEY, mAccessToken);

        long uid = Long.parseLong(mAccessToken.getUid());
        mUsersAPI.show(uid,new RequestListener() {
            @Override
            public void onComplete(String s) {
                try {
                    JSONObject object=new JSONObject(s);
                    LoginUser user=new LoginUser();
                    user.parseWeiboJSON(object);

                    //获取用户信息后，注册用户
                    registerSINA(user);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onWeiboException(WeiboException e) {

            }
        });
    }

    /**
     * 注册新浪第三方账号
     * @param user
     */
    private void registerSINA(LoginUser user){
        if(user==null){
            return;
        }
        if(mAccessToken==null){
            return;
        }
        if(!mAccessToken.isSessionValid()){
            return;
        }
        HttpUtils httpUtils=new HttpUtils();
        String registerUrl = "http://kxai.cn/qms/ws/user/registerByOpen.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("token","30e65bb3f2201815e2b4f09abfc5d36b");
        params.addBodyParameter("accessToken",mAccessToken.getToken());
        params.addBodyParameter("uid",mAccessToken.getUid());
        params.addBodyParameter("openPlat","SINA");
        params.addBodyParameter("nickname",user.getNickname());
        params.addBodyParameter("sex",user.getSex()+"");
        httpUtils.send(HttpRequest.HttpMethod.POST, registerUrl, params,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                //注册成功，存储用户信息
                LoginUser user=new LoginUser();
                String result = objectResponseInfo.result.toString();
                if(result==null){
                    return;
                }

                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response = object.optJSONObject("response");
                    String token=response.optString("token");
                    SPHelper instance = SPHelper.getInstance();
                    instance.setToken(token);
                    if(response==null){
                        return;
                    }
                    JSONObject jsonObject = response.optJSONObject("user");
                    if(jsonObject==null){
                        return;
                    }
                    user.parseJSON(jsonObject);
                    UserHelper userHelper = UserHelper.getInstance();
                    userHelper.setUser(user);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                //TODO 注册失败
                Log.d("注册失败",s);
            }
        });
        checkUserLogin();
    }


    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see {@link android.app.Activity#onActivityResult}
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResult
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }


    private void initView() {
        //添加fragment数据
        fragmentList=new ArrayList<>();
        fragmentList.add(new SpaceMineConnectionFragment());
        fragmentList.add(new SpaceMineWorksFragment());
        fragmentList.add(new SpaceMineTopicFragment());
        fragmentList.add(new SpaceMinePartFragment());
        //初始化界面
        transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.space_fragment_content, fragmentList.get(0));
        transaction.commit();
        int id = rgSelect.getChildAt(0).getId();
        rgSelect.check(id);

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i=0;i<group.getChildCount();i++){
            int id = group.getChildAt(i).getId();
            if(id==checkedId){
                transaction=getFragmentManager().beginTransaction();
                transaction.replace(R.id.space_fragment_content, fragmentList.get(i));
                transaction.commit();
            }
        }
    }

    @Override
    public void onLeftButtonClick() {
        startActivity(new Intent(getActivity(), SpaceSettingActivity.class));
        getActivity().overridePendingTransition(R.anim.trans_slider_in,0);
    }

    @Override
    public void onRightButtonClick() {

    }

    @Override
    public void onSearchButtonClick() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.space_email:
                startActivity(new Intent(getActivity(), SpaceMessageActivity.class));
                getActivity().overridePendingTransition(R.anim.trans_slider_in,0);
                break;
            case R.id.fragment_main_my_space_userinfo:
                Intent intent = new Intent(getActivity(), ActivityUserMessage.class);
                startActivityForResult(intent,101);
                getActivity().overridePendingTransition(R.anim.trans_slider_in,0);
                break;
            case R.id.fragment_main_my_space_login:
                loginDialog.show();
                break;
            case R.id.user_login_weibo:
                mSsoHandler.authorize(new AuthListener());
                break;
            case R.id.user_login_qq:
                break;
        }

    }



    /**
     * 微博认证授权回调类。
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     *    该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                // 显示 Token
                //updateTokenView(false);
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(getActivity(), mAccessToken);
                Toast.makeText(getActivity(),
                        R.string.weibosdk_demo_toast_auth_success, Toast.LENGTH_SHORT).show();
                setUserInfoAfterAuth();
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = getString(R.string.weibosdk_demo_toast_auth_failed);
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
            }
            loginDialog.cancel();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getActivity(),
                    R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_LONG).show();
            loginDialog.cancel();

        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(getActivity(),
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
            loginDialog.cancel();
        }
    }
}
